package main

import (
	"adm-mysql/handler"
	"adm-mysql/utils"
	"context"
	"errors"
	"flag"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

var (
	addr = flag.String("a", ":8080", "listen address")
	conf = flag.String("c", "conf/app.yaml", "配置文件路径")
)

func init() {
	flag.Parse()
	utils.InitConf(*conf)
	utils.InitDB()
}

func main() {
	defer utils.DB.Close()
	router := handler.NewRouter()
	srv := &http.Server{
		Addr:         *addr,
		Handler:      router,
		ReadTimeout:  3 * time.Second,
		WriteTimeout: 5 * time.Second,
	}

	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			slog.Error("server listen is error. ", "address", *addr, "err", err)
		}
	}()
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGTERM, syscall.SIGINT)
	<-quit
	slog.Info("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()

	if err := srv.Shutdown(ctx); err != nil {
		slog.Error("Server Shutdown Error:", "err", err)
	}
	select {
	case <-ctx.Done():
		slog.Error("timeout of 2 seconds.")
	}
	slog.Info("Server Shutdown Successed.")
}
